`timescale 1ns / 1ns

module iic_slave (rst,clk,scl,sda,addr);

input rst;
input clk;

inout scl;
inout sda;
input [6:0] addr;

wire oda;
reg ready;

reg ioctl;
reg busy;

assign scl = ready ? 1'bz : 1'b0;
assign sda = ioctl ? oda : 1'bz;

parameter   STATE_IDLE = 4'd0,
            STATE_ADDR = 4'd1,
            STATE_RUN = 4'd2,
            STATE_READ = 4'd3,
            STATE_WRITE = 4'd4;

reg [3:0] state;
reg [3:0] counter;

reg [7:0] temp;
reg rw;

always @(posedge rst) begin
    busy <= 1'b0;
    ioctl <= 1'b0;
    state <= STATE_IDLE;
    ready <= 1'b1;
end

always @(posedge scl) begin
    if (busy == 1'b1) begin
        case (state)
            STATE_ADDR: begin
                temp <= {sda, temp[7:1]};
                if (counter == 4'd6) begin
                    if (temp[6:0] == addr) begin
                        state <= STATE_RUN;
                    end else begin
                        state <= STATE_IDLE;
                    end
                end else begin
                    counter <= counter + 1'b1;
                end
            end
            STATE_RUN: begin
                rw <= sda;
            end
        endcase
    end
end

always @(edge sda) begin
    if (scl == 1'b1) begin
        if (sda) begin
            state <= STATE_IDLE;
        end else begin
            state <= STATE_ADDR;
            counter <= 4'd0;
        end
    end
end

endmodule

